package org.lilred.nzbberry.util;

import net.rim.device.api.math.Fixed32;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;

/**
 * Provides utility methods for scaling an EncodedImage
 */
public class ScaleImage {
	/**
	 * Stretches the encoded image to a size.
	 * @param	encoded		the source encoded image
	 * @param	newWidth 	the destination width
	 * @param	newHeight	the destination height
	 * @return	the stretched image
	 */
	public static EncodedImage toSize(EncodedImage encoded, int newWidth, int newHeight) {
		int curWidth = encoded.getWidth();
		int curHeight = encoded.getHeight();
		int xnumerator = Fixed32.toFP(curWidth);
		int xdenominator = Fixed32.toFP(newWidth);
		int xscale = Fixed32.div(xnumerator, xdenominator);
		int ynumerator = Fixed32.toFP(curHeight);
		int ydenominator = Fixed32.toFP(newHeight);
		int yscale = Fixed32.div(ynumerator, ydenominator);
		return encoded.scaleImage32(xscale, yscale);
	}
	
	/**
	 * Scales an image to fit a specified rectangle (constraining proportions).
	 * @param	encoded	the source encoded image
	 * @param	width	the width to fit the resized image in
	 * @param	height	the height to fit the resized image in
	 * @return	scaled encoded image
	 */
	public static Bitmap toFit(EncodedImage encoded, int width, int height) {
		int curWidth = encoded.getWidth();
		int curHeight = encoded.getHeight();
		int xnumerator = Fixed32.toFP(curWidth);
		int xdenominator = Fixed32.toFP(width);
		int xscale = Fixed32.div(xnumerator, xdenominator);
		int ynumerator = Fixed32.toFP(curHeight);
		int ydenominator = Fixed32.toFP(height);
		int yscale = Fixed32.div(ynumerator, ydenominator);		
		int scale = Math.max(xscale, yscale);
		return encoded.scaleImage32(scale, scale).getBitmap();
	}
	
	/**
	 * Scales an image horizontally to the specified width (constraining proportions).
	 * @param 	encoded		the source encoded image
	 * @param	newWidth	the width to scale to
	 * @return	scaled encoded image
	 */
	public static EncodedImage toWidth(EncodedImage encoded, int newWidth) {
		return scaleToFactor(encoded, encoded.getWidth(), newWidth);
	}
	
	/**
	 * Scales an image vertically to the specified width (constraining proportions).
	 * @param 	encoded		the source encoded image
	 * @param	newHeight	the height to scale to
	 * @return 	scaled encoded image
	 */
	public static EncodedImage toHeight(EncodedImage encoded, int newHeight) {
		return scaleToFactor(encoded, encoded.getHeight(), newHeight);
	}

	private static EncodedImage scaleToFactor(EncodedImage encoded, int curSize, int newSize) {
		int numerator = Fixed32.toFP(curSize);
		int denominator = Fixed32.toFP(newSize);
		int scale = Fixed32.div(numerator, denominator);

		return encoded.scaleImage32(scale, scale);
	}	
}
